let ctx = canvas.getContext('2d')

import global from './global'
import Music from './music'
import BackGround from './background'
import Player from './player'
import Enemy from './enemy'
import GameInfo from './gameinfo'

export default class Main {
  constructor() {
    
    this.bindLoop = this.loop.bind(this)

    this.music = new Music()
    this.bg = new BackGround()
    this.player = new Player()
    this.gameInfo = new GameInfo()

    this.aniId = window.requestAnimationFrame(
      this.bindLoop,
      canvas
    )
  }

  restart() {
    global.reset()
    canvas.removeEventListener('touchstart', this.touchHandler)
    // 玩家位置重置
    this.player.reset()
    // 清除上一局的动画
    window.cancelAnimationFrame(this.aniId);
    // 重新开始动画帧
    this.aniId = window.requestAnimationFrame(
      this.bindLoop,
      canvas
    )
  }
  update(){
    this.bg.update()
    // 敌机位置更新
    global.enemys.forEach(enemy => {
      enemy.update()
    })
    // 子弹位置更新
    global.bullets.forEach(bullet => {
      bullet.update()
    })
    // 碰撞检测
    this.collisionDetection()
  }

  render (){
    // 清空区域
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    // 重绘背景
    this.bg.render(ctx)
    // 重绘玩家
    this.player.render(ctx)
    // 重绘敌机
    global.enemys.forEach(enemy => {
      enemy.render(ctx)
    })
    // 重绘子弹
    global.bullets.forEach(bullet => {
      bullet.render(ctx)
    })
    // 发射子弹
    if (global.frame % 20 == 0){
      this.player.shoot()
      this.music.playShoot()
    }
    // 生成敌机
    if (global.frame % 30 == 0) {
      this.generteEnemy()
    }
    // 重绘信息
    this.gameInfo.render(ctx)
    // 是否游戏结束
    if(global.gameOver){
      this.gameInfo.renderGameOver(ctx)
    }
  }
  
  // 实现游戏帧循环
  loop() {
    if (global.gameOver){
      this.touchHandler = this.touchEventHandler.bind(this)
      canvas.addEventListener('touchstart', this.touchHandler)
      return
    }
    global.frame ++
    this.update()
    this.render()
    this.aniId = window.requestAnimationFrame(
      this.bindLoop,
      canvas
    )
  }

  // 生成敌机
  generteEnemy(){
    let enemy = new Enemy()
    enemy.init(6)
    global.enemys.push(enemy)
  }

  // 碰撞检测 
  collisionDetection(){
    global.bullets.forEach(bullet => {
      global.enemys.forEach(enemy=>{
        // 子弹是否触碰到敌机
        if (enemy.isCollideWith(bullet)) {
          global.gameInfo.score++
          enemy.visible = false
          enemy.playAnimation()
          this.music.playExplosion()
        }
      })
    })
    // 是否触碰到敌机
    global.enemys.forEach(enemy => {
      if (this.player.isCollideWith(enemy)) {
        global.gameOver = true
      }
    })
  }

  touchEventHandler(e){
    e.preventDefault()

    let x = e.touches[0].clientX
    let y = e.touches[0].clientY

    let area = this.gameInfo.btnArea
    let onX = x >= area.startX && x <= area.endX
    let onY = y >= area.startY&& y <= area.endY

    if (onX && onY){
      this.restart()
    }
  }

}